package com.msb.mall.product.service.impl;

import com.msb.mall.product.service.CategoryBrandRelationService;
import com.msb.mall.product.vo.Catalog2VO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.mall.common.utils.PageUtils;
import com.msb.mall.common.utils.Query;

import com.msb.mall.product.dao.CategoryDao;
import com.msb.mall.product.entity.CategoryEntity;
import com.msb.mall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询商品类别属性结构
     * @param params
     * @return
     */
    @Override
    public List<CategoryEntity> queryPageWithTree(Map<String, Object> params) {
        // 1. 查询所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 2. 组装成父子结构
        // 第一步循环所有大类，查询其子类
        List<CategoryEntity> categoryEntityList = categoryEntities.stream().filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
                    // 根据大类找到多有的小类，递归的方式实现
                    categoryEntity.setChildrens(getCategoryChildren(categoryEntity, categoryEntities));
                    return categoryEntity;
                }).sorted((category1, category2) -> {
                    return (category1.getSort() == null ? 0 : category1.getSort()) - (category2.getSort() == null ? 0 : category2.getSort());
                }).collect(Collectors.toList());
        return categoryEntityList;
    }

    @Override
    public void removeCategoryByIds(List<Long> catIds) {
        // TODO 1.检查类别数据是否在其他业务中使用

        // 2.批量逻辑删除操作
        baseMapper.deleteBatchIds(catIds);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPaths = findParentPath(catelogId, paths);
        Collections.reverse(parentPaths);
        return parentPaths.toArray(new Long[parentPaths.size()]);
    }

    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    /**
     * 获得所有商品的大类（一级分类）
     * @return
     */
    @Override
    public List<CategoryEntity> getLeva1Category() {
        return baseMapper.queryLeva1Category();
    }


    public List<CategoryEntity> queryByParentCid(List<CategoryEntity> list, Long parentCid) {
        return list.stream().filter(categoryEntity -> categoryEntity.getParentCid().equals(parentCid)).collect(Collectors.toList());
    }

    @Override
    public Map<String, List<Catalog2VO>> getCategory2JSON() {
        List<CategoryEntity> list = baseMapper.selectList(new QueryWrapper<CategoryEntity>());
        // 获取一级分类的数据，
        List<CategoryEntity> categoryEntities = queryByParentCid(list, 0L);
        // 转换成 Map<String, Catalog2VO>，map的key是一级分类的id，value是Catalog2VO对象
        Map<String, List<Catalog2VO>> map = categoryEntities.stream().collect(
                Collectors.toMap(key -> key.getCatId().toString(), l1 -> {
                    // 根据一级分类的id查询其对应的二级分类
//                    List<CategoryEntity> catagory2 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l1.getCatId()));
                    List<CategoryEntity> catagory2 = queryByParentCid(list, l1.getCatId());
                    List<Catalog2VO> catalog2VOS = null;
                    if (catagory2 != null) {
                        catalog2VOS = catagory2.stream().map(l2 -> {
                            Catalog2VO catalog2VO = new Catalog2VO(l1.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            // 根据二级分类的id查询其对应的三级分类
//                            List<CategoryEntity> catagory3 = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", l2.getCatId()));
                            List<CategoryEntity> catagory3 = queryByParentCid(list, l2.getCatId());
                            List<Catalog2VO.Catalog3VO> catalog3VOList = catagory3.stream().map(l3 -> {
                                Catalog2VO.Catalog3VO catalog3VO = new Catalog2VO.Catalog3VO(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                return catalog3VO;
                            }).collect(Collectors.toList());
                            catalog2VO.setCatalog3List(catalog3VOList);
                            return catalog2VO;
                        }).collect(Collectors.toList());
                    }
                    return catalog2VOS;
                })
        );
        return map;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查询子类
     * @param categoryEntity    某个大类
     * @param categoryEntities  所有分类
     * @return 给定类别实体的子类别列表
     */
    private List<CategoryEntity> getCategoryChildren(CategoryEntity categoryEntity, List<CategoryEntity> categoryEntities) {
        List<CategoryEntity> list = categoryEntities.stream().filter(category -> {
            // 根据大类找到他的直属小类
            // 注意： Long 数据比较 不在-128 ~ 127 之间的数据是 new Long() 对象，需要用 equals() 方法比较
            return category.getParentCid().equals(categoryEntity.getCatId());
        }).map(category -> {
            // 根据这个小类递归查询找到对应的小小类
            category.setChildrens(getCategoryChildren(category, categoryEntities));
            return category;
        }).sorted((entity1, entity2) -> {
            return (entity1.getSort() == null ? 0 : entity1.getSort()) - (entity2.getSort() == null ? 0 : entity2.getSort());
        }).collect(Collectors.toList());
        return list;
    }

}